﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Flurl;
using Newtonsoft.Json;
using WebSocket4Net;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.Core.Log;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Response;
using ZilLion.TaskManager.Entity.SokectMessage;

namespace ZilLion.TaskManager.Core.Infrastructure
{
    public enum Loglevel
    {
        Trace,
        Info,
        Warn,
        Success,
        Error
    }

    /// <summary>
    ///     打印输出信息
    /// </summary>
    public static class CustomTaskLogger
    {
        private static WebSocket _webSocket;

        public static WebSocket GetWebSocket()
        {
            try
            {
                if (_webSocket == null)
                {
                    var url = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost, "Api",
                        "Jwt",
                        "GetJwt", "websocket"
                    );
                    var token = HttpHelper.HttpRequestPost<Dictionary<string, string>, TokenResponse>(url,
                        new Dictionary<string, string>
                        {
                            {
                                "clinetKey", JsonConvert.SerializeObject(new SocketKeyDto
                                {
                                    ClientNo = ZilLionConfigurationManager
                                        .GetConfigInstance<TaskManagerCommonConfig>().ClientNo,
                                    ClientType = "Container"
                                })
                            }
                        });
                    if (token?.Token.IsNotNullOrEmpty() ?? false)
                    {
                        var sockethost = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost,
                            "websocket",
                            "TaskPlatform"
                        ).ToLower().Replace("http:", "ws:").Replace("https:", "ws:");
                        var websocket = new WebSocket($"{sockethost}?token={token?.Token}");
                        websocket.Opened += (s, arg) => { };
                        websocket.Error += (s, arg) => { ZilLionLogManager.Instance().Error(arg.Exception); };
                        websocket.Closed += (s, arg) => { ZilLionLogManager.Instance().Warn("Socket连接已关闭"); };
                        websocket.MessageReceived += (s, arg) =>
                        {
                            if (ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().Traceable)
                                ZilLionLogManager.Instance()
                                    .Trace(
                                        $"{ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo}-->{arg.Message}");
                        };

                        websocket.Open();
                        _webSocket = websocket;
                    }
                    else
                    {
                        ZilLionLogManager.Instance().Warn("Socket连接JWT非法");
                    }
                }
            }
            catch (Exception e)
            {
               
            }


            return _webSocket;
        }

        /// <summary>
        ///     输出信息
        /// </summary>
        /// <param name="loglevel"></param>
        /// <param name="message"></param>
        /// <param name="title"></param>
        public static void Print(Loglevel loglevel, string message, string title = "")
        {
            switch (loglevel)
            {
                case Loglevel.Trace:
                    if (ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().Traceable)
                        ZilLionLogManager.Instance().Trace($"{title}-->{message}");
                    break;
                case Loglevel.Info:
                    ZilLionLogManager.Instance().Info($"{title}-->{message}");
                    break;
                case Loglevel.Warn:
                    ZilLionLogManager.Instance().Warn($"{title}-->{message}");
                    break;
                case Loglevel.Success:
                    if (ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().Traceable)
                        ZilLionLogManager.Instance().Trace($"{title}-->{message}");
                    break;
                default:
                    ZilLionLogManager.Instance().Info($"{title}-->{message}");
                    break;
            }
            if (loglevel == Loglevel.Trace &&
                !ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().Traceable)
                return;
            Task.Run(() =>
            {
                GetWebSocket()?.Send(JsonConvert.SerializeObject(new SocketMessage
                {
                    MessageId = Guid.NewGuid().ToString(),
                    MessageType = "TASKCLIENTLOG",
                    Data = JsonConvert.SerializeObject(new LogDto
                    {
                        Loglevel = loglevel,
                        LogMessage = message,
                        LogTime = DateTime.Now
                    })
                }));
            });
        }

        public static void Print(Exception ex, string title = "")
        {
            var errorid = Guid.NewGuid().ToString("N");
            ZilLionLogManager.Instance().Error(ex, tags: errorid + title);
            Task.Run(() =>
            {
                GetWebSocket()?.Send(JsonConvert.SerializeObject(new SocketMessage
                {
                    MessageId = Guid.NewGuid().ToString(),
                    MessageType = "TASKCLIENTLOG",
                    Data = JsonConvert.SerializeObject(new LogDto
                    {
                        Loglevel = Loglevel.Error,
                        LogMessage =
                            $"{title}-->错误ID:{errorid}{Environment.NewLine}发生错误:{ex.GetType()}{Environment.NewLine}{ex.Message}{Environment.NewLine}{ex.StackTrace}",
                        LogTime = DateTime.Now
                    })
                }));
            });
        }
    }
}